<template>
  <div class="c-fc-xblack c-fs24 c-bg-sgray">
    <div class="c-pv30 c-ph24 c-w100 c-br10 c-bg-white" v-if="scheduleDetail != null">
      <div class="c-flex-row c-p">
        <div class="c-ww180 c-hh120 c-text-hidden c-p">
          <div class="c-p c-ww180 c-hh120">
            <CoverImg :coverSizeClass="'c-w100 c-h c-br16 c-text-hidden'" imgClass="c-br16" :coverUrl="$addXossFilter(((scheduleDetail.saleCourseId == null || scheduleDetail.saleCourseId == 0) ? scheduleDetail.courseCover : (scheduleDetail.saleCourseCover)), require('../../../public/i/wap/edu/enlist.png'))" />
            <div class="c-pa c-p-b8 c-p-r8 c-br8 c-fs18 c-fc-white c-ph5 c-hh28 c-flex-row c-flex-center c-translucent-balck50">{{scheduleDetail.teachType != 2 ? '线下课' : '线上课'}}</div>
          </div>
          <img class="c-pa c-p-t-1 c-p-l0 c-ww76 c-hh32 c-br-tl16" :src="'https://ck-bkt-knowledge-payment.oss-cn-hangzhou.aliyuncs.com/admin/material/9_material_admin/image/public/i/wap/edu/' + (scheduleDetail.courseType=='体验课' ? 'experience' : 'formal') + '.png'" />
        </div>
        <div class="c-ml20 c-flex-column c-w0 c-flex-grow1 c-justify-sb">
          <div class="c-fw400 c-lh36 c-fc-xblack c-fw-b c-text-ellipsis2">
            {{scheduleDetail.courseName}}
          </div>
          <div class="c-fs20 c-fc-gray" v-if="scheduleDetail.teacherName != null">教师：{{scheduleDetail.teacherName}}</div>
          <div class="c-fs20 c-fc-gray" v-if="scheduleDetail.startTime != null && scheduleDetail.endTime != null">时间：{{isSameDay(scheduleDetail.startTime, scheduleDetail.endTime) ? scheduleDetail.beginTime : `${scheduleDetail.startTime}-${scheduleDetail.endTime}`}}</div>
        </div>
      </div>
      <template v-if="scheduleDetail.schoolName != null">
        <div class="c-mt30 c-hh80 c-bd-b1 c-bd-t1 c-flex-row c-aligni-center c-fs22 c-fc-gray">
          校区：{{scheduleDetail.schoolName}}&nbsp;<span class="c-fs28 c-pt6" v-if="scheduleDetail.schoolRoomName">/</span><span v-if="scheduleDetail.schoolRoomName">&nbsp;教室：{{scheduleDetail.schoolRoomName}}</span>
        </div>
        <div class="c-mt20 c-flex-row c-aligni-center c-justify-sb c-w100 c-fc-gray" @click="goLocation">
          <div class=" c-flex-grow1 c-flex-row c-aligni-center">
            <div class="c-ww40 c-hh40 c-brp50 c-mr10 c-flex-shrink0">
              <img class="c-w100 c-brp50" :src="$addXossFilter('https://knowledge-payment.oss-cn-beijing.aliyuncs.com/goodsBanners/2020-04-27/zG06Jg0PC7d7ykps54vpiywTxKpO4yKFbq6MRLaI.png')"
                alt="">
            </div>
            <div class="c-text-ellipsis1 c-w0 c-flex-grow1 c-fs22 ">{{scheduleDetail.provinceName + scheduleDetail.cityName + scheduleDetail.areaName + scheduleDetail.details}}</div>
          </div>
          <div class="iconfont c-fs18 c-ww44 c-textAlign-r c-flex-shrink0">&#xe908;</div>
        </div>
      </template>
    </div>
    <div class="c-pv30 c-ph24 c-bg-white c-mt20" v-if="scheduleDetail != null">
      <div class="c-flex-row c-justify-sb c-aligni-center c-pb30 c-bd-b1">
        <div class="c-flex-row c-aligni-center">
          课程信息
          <span class="c-ml30 c-fc-white c-br4 c-mww60 c-ph8 c-pv2 c-fs16 c-textAlign-c"
            :class="scheduleDetail.signStatus == 0 ? 'c-bg-FF5355' : scheduleDetail.signStatus == 1 ? 'c-bg-sblue' : scheduleDetail.signStatus == 3 ? 'c-bg-mgreen' : 'c-bg-ccc'"
            v-if="scheduleDetail.signStatus != null && ((scheduleDetail.status == 1 && scheduleDetail.reservationStatus >= 3 && isShowAppointment == 2) || isShowAppointment == 1)">{{scheduleDetail.signStatus == 0 ? "未签到" : scheduleDetail.signStatus == 1 ? "已签到" : scheduleDetail.signStatus == 2 ? "未到" : scheduleDetail.signStatus == 3 ? "请假" : ""}}</span>
        </div>
        <!--canReservation:0不可预约 1可预约; status:0未预约 1已预约 -->
        <div v-if="(scheduleDetail.canReservation != 0 && scheduleDetail.saleType != 3) || scheduleDetail.saleType == 3 || scheduleDetail.courseType == '体验课'" @click="appointment(scheduleDetail.id, scheduleDetail.saleCourseId)" class=" c-hh42 c-lh42 c-fc-white c-fs20 c-textAlign-c c-br21"
          :class="(scheduleDetail.saleType == 3 || scheduleDetail.canReservation == 0 || scheduleDetail.courseType == '体验课') ? 'c-bg-ccc imgCloseBig c-ph24' : scheduleDetail.status ==0 && scheduleDetail.unAppointNum > 0 && getTimeMM(scheduleDetail.startTime) ? 'theme-bg-gradient c-ww110' : (scheduleDetail.status == 1 ? 'c-bg-ccc c-ph24' : 'c-bg-ccc imgCloseBig c-ph24')">
          {{scheduleDetail.courseType == '体验课' ? '不可取消' : scheduleDetail.saleType == 3 ? '班级课程' : (scheduleDetail.status ==1 || scheduleDetail.canReservation == 0) ? '取消预约' : scheduleDetail.status ==0 && scheduleDetail.unAppointNum > 0 ? '预约' : '名额已满'}}
        </div>
      </div>
      <div class="c-mt30 c-flex-row c-aligni-center">
        学员: {{scheduleDetail.studentName}}
      </div>
      <div class="c-mt30 c-text-ellipsis1" v-if="scheduleDetail.saleType == 1">课时:
        {{Number(scheduleDetail.periodNum) - Number(scheduleDetail.consume == null ? 0 : scheduleDetail.consume)+'(剩) '}}/{{' ' + scheduleDetail.periodNum}}(总)</div>
      <div class="c-mt30 c-text-ellipsis1" v-if="scheduleDetail.signStatus >= 1">签到时间 ({{scheduleDetail.signStatus == 1 ? '签到' : scheduleDetail.signStatus == 2 ? '未到' : '请假'}}):
        {{scheduleDetail.signTime}}</div>
      <div class="c-mt30 c-text-ellipsis1" v-if="scheduleDetail.appointNum > 0">预约名额: {{Number(scheduleDetail.unAppointNum)+'(剩) '}}/{{' ' + scheduleDetail.appointNum}}(总)</div>
    </div>
    <div class="c-pv30 c-ph24 c-bg-white c-mt20">
      <div class="c-bd-b1 c-pb30 c-fc-gray">课节信息</div>
      <div class="c-minh110">
        <div class=" c-flex-row c-aligni-start c-fw-b c-fs26" v-if="scheduleDetail.lessonName">
          <div class="c-mt30 c-lh36 c-w0 c-flex-grow1">{{scheduleDetail.lessonName}}</div>
        </div>
        <div class="c-flex-column c-fs24" v-if="scheduleDetail.lessonDetail">
          <div class="c-mt30 c-lh36" v-html="scheduleDetail.lessonDetail"></div>
        </div>
      </div>

    </div>
    <!-- x新增直播 -->
    <template v-if="scheduleDetail.teachType == 2 && scheduleDetail.status == 1 && scheduleDetail.reservationStatus != -1 && scheduleDetail.isAllow != -1">
      <template v-if="scheduleDetail.liveStatus == 1">
        <!-- 等待课程开始 -->
        <div class="c-w100 c-maxw640 c-hh100 c-bd-t1 c-bg-white c-pf c-p-b0 c-flex-row c-aligni-center c-ph24">
          <div class="c-w100 c-hh64 c-fc-white c-fs28 c-flex-row c-flex-center c-br30 c-bg-d7">等待课程开始</div>
        </div>
      </template>
      <template v-if="scheduleDetail.liveStatus == 2">
        <!-- 直播开始 -->
        <div class="c-w100 c-maxw640 c-hh100 c-bd-t1 c-bg-white c-pf c-p-b0 c-flex-row c-aligni-center c-ph24" @click="handleClickLive">
          <div class="c-w100 c-hh64 c-fc-white c-fs28 c-flex-row c-flex-center c-br30 theme-bg-gradient">
            {{scheduleDetail.signStatus == 0 || scheduleDetail.signStatus == 2 || scheduleDetail.signStatus == 3 ? '签到并开始上课' : scheduleDetail.signStatus == 1 ? '开始上课' : ''}}</div>
        </div>
      </template>
      <template v-if="scheduleDetail.liveStatus == 3">
        <!-- 回顾课程 -->
        <div class="c-w100 c-maxw640 c-hh100 c-bd-t1 c-bg-white c-pf c-p-b0 c-flex-row c-aligni-center c-ph24" @click="handleClickLive">
          <div class="c-w100 c-hh64 c-fc-white c-fs28 c-flex-row c-flex-center c-br30 theme-bg-gradient">回顾课程</div>
        </div>
      </template>
      <template v-if="scheduleDetail.liveStatus == 4">
        <!-- 已结束 -->
        <div class="c-w100 c-maxw640 c-hh100 c-bd-t1 c-bg-white c-pf c-p-b0 c-flex-row c-aligni-center c-ph24">
          <div class="c-w100 c-hh64 c-fc-white c-fs28 c-flex-row c-flex-center c-br30 c-bg-d7">已结束</div>
        </div>
      </template>
    </template>
  </div>
</template>

<script>

import { utilJs } from "@/utils/common";
import CoverImg from '@/components/templates/common/coverImg.vue';
export default {
  name: 'ScheduleDetail',
  components: {
    CoverImg
  },
  props: [],
  beforeCreate() {

  },
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
      scheduleDetail: {},
      courseId: "",
      studentId: "",
      scheduleListId: "",
      purchaseId: "",
      // saleCourseId: "",
      type: "",
      isShowAppointment: "", //2有预约 和取消预约功能，1.签到，请假，未到
      orderId: '', // 订单id
      reservationResStatus: false, // // 预约请求状态，防止请求未结束再次请求
      saleCourseId: '',
      isClick: false,
    }
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() { },
  watch: { },
  computed: {
    // 判断是否跨天
    isSameDay() {
      return function (start, end) {
        let startTime = new Date(start);
        let endTime = new Date(end);
        let isSameDay = startTime.getFullYear() == endTime.getFullYear() && startTime.getMonth() == endTime.getMonth() && startTime.getDate() == endTime.getDate();
        return isSameDay;
      }
    }
  },
  methods: {
    goSingIn() {
      if (this.isClick) {
        return;
      }
      this.isClick = true;
      utilJs.postMethod(global.apiurl + "educationSystem/reservation/sign", { id: this.scheduleDetail.id }, res => {
        this.isClick = false;
        if (Array.isArray(res)) {
          if (this.scheduleDetail.signStatus == 0 || this.scheduleDetail.signStatus == 2 || this.scheduleDetail.signStatus == 3) {
            // 0 未签到，2 未到 3 请假
            this.$showCjToast({
              text: "签到成功",
            });
          }
          if (this.scheduleDetail.inSocialRoom != 1) {
            this.addUserToSocailRoom();
          } else {
            this.routerGoRoom();
          }
        } else {
          this.$cjConfirm({
            title: '提示',
            message: `课程开始前${res.signBeforeHour}小时可签到，课程结束后${res.signAfterHour}小时停止签到`,
            showCancelButton: false,
            clickCloseModal: false
          })
        }
      }, failRes => {
        this.isClick = false;
      })
    },
    setRoomNickname() {
      utilJs.postMethod(global.apiurl + "educationSystem/schedule/socialRoomMember", { studentId: this.studentId, socialRoomId: this.scheduleDetail.socialRoomId });
    },
    handleClickLive() {
      let state = this.scheduleDetail.liveStatus;
      // 1 等待课程开始 2 签到并开始上课 3 回顾课程 4 已结束
      if (state == 2 || state == 3) {
        this.goSingIn();
      }
    },
    addUserToSocailRoom() {
      let postData = {
        "socialRoomId": this.scheduleDetail.socialRoomId,
      };
      utilJs.postMethod(global.apiurl + "social/addSocialRoom", postData, res => {
        this.setRoomNickname();
        this.routerGoRoom();
      });
    },
    routerGoRoom() {
      let goPath = 'liveRoom';
      if (this.scheduleDetail.playType == 2) {
        goPath = 'liveVerticalRoom'
      }
      this.$routerGo(this, "push", { path: `/homePage/live/${goPath}?liveId=${this.scheduleDetail.liveId}&SocialRoomId=${this.scheduleDetail.socialRoomId}&eduId=${this.scheduleDetail.id}` });
    },
    //判断时间大小
    getTimeMM(str) {
      let stime = utilJs.getTimeByDate(str);
      let nowTime = (new Date()).getTime();
      return stime > nowTime ? true : false;
    },
    getScheduleDetail() {
      let _this = this;
      utilJs.getMethod(global.apiurl + "educationSystem/schedule/info?studentId=" + this.studentId + "&courseId=" + this.courseId + "&scheduleListId=" + this.scheduleListId + "&id=" + this.orderId, res => {
        this.scheduleDetail = res;
        this.purchaseId = res.purchaseId;
        this.type = res.courseType;
        this.courseId = res.courseId || ''
        this.studentId = res.studentId || ''
        this.saleCourseId = res.saleCourseId || ''
        this.wechatShare();
      }, failRes => {
        Vue.prototype.$showCjToast({
          text: failRes.data != null && failRes.data.msg != null ? failRes.data.msg : "系统错误",
          type: 'warn',
        });
        _this.$routerGo(_this, "push", {
          path: "/edu/faceTeaching"
        });
      })
    },
    goLocation() {
      this.$routerGo(this, "push", { path: '/addressLocation', query: { address: (this.scheduleDetail.provinceName + this.scheduleDetail.cityName + this.scheduleDetail.areaName + this.scheduleDetail.details) } })
    },
    cancelReservation(id) {
      let data = {
      }
      data._method = 'put';
      utilJs.postMethod(global.apiurl + "educationSystem/reservation/" + id, data, res => {
        if (!!res.reserveSetting) {
          //是否有取消预约限制
          if (res.reserveSetting.isCancelLimit == 1) {
            this.$cjConfirm({
              title: '提示',
              message: `上课前${res.reserveSetting.cancelHour}小时可取消`,
              showCancelButton: false,
              clickCloseModal: false
            })
            this.reservationResStatus = false;
          } else {
            this.$cjConfirm({
              title: '提示',
              message: `预约后无法在学员端取消`,
              showCancelButton: false,
              clickCloseModal: false
            })
            this.reservationResStatus = false;
          }
        } else {
          this.reservationResStatus = false;
          this.scheduleDetail = {};
          this.getScheduleDetail();
        }
      }, failRes => {
        this.reservationResStatus = false;
      })
    },
    appointment(id, saleCourseId) {
      if (!this.getTimeMM(this.scheduleDetail.startTime)) {
        this.$showCjToast({
          type: 'warn',
          text: "课程已开始，不能进行操作"
        });
        return;
      }
      if (this.reservationResStatus || this.scheduleDetail.canReservation == 0 || this.scheduleDetail.courseType == '体验课') {
        return;
      }
      this.reservationResStatus = true;
      if (this.scheduleDetail.status) {
        //1 已经预约 调用取消预约接口
        this.$cjConfirm({
          title: '提示',
          message:  "预约名额剩" + this.scheduleDetail.unAppointNum + "个，确定取消预约？",
          onConfirm:() => {
            this.reservationResStatus = false;
            this.cancelReservation(id);
          },
          onCancel:() => {
            this.reservationResStatus = false;
          }
        })
      } else {
        // 0 未预约 调用预约接口
        let reserveType = this.type == "正式课" ? 2 : 1;
        utilJs.postMethod(global.apiurl + "educationSystem/reservation", { courseId: this.courseId, studentId: this.studentId, scheduleListId: this.scheduleListId, purchaseId: this.purchaseId, saleCourseId: saleCourseId, reserveType: reserveType }, res => {
          if (!!res.reserveSetting) {
            //是否有预约限制
            this.$cjConfirm({
              title: '提示',
              message: `可预约${res.reserveSetting.reserveDay}天内的课程, 课程开始前${res.reserveSetting.reserveTime}小时停止预约`,
              showCancelButton: false,
              clickCloseModal: false
            })
            this.reservationStatus = false;
          } else {
            this.$showCjToast({
              text: "预约成功",
            });
            //预约成功返回consume,没算上之前预约消耗,剩余课时对不上,不能用this.$set();
            this.getScheduleDetail();
            this.reservationResStatus = false;
          }
        }, failRes => {
          this.reservationResStatus = false;
        })
      }
    },
    //分享
    wechatShare: function () {
      let title = this.scheduleDetail.courseName;
      let shareImg = this.scheduleDetail.saleCourseCover || this.scheduleDetail.courseCover || 'https://knowledge-payment.oss-cn-beijing.aliyuncs.com/13/resource/admin-fe_lj7l_enlist_YeT7sJt3W2MmhWQreXZa.png' || window.localStorage.getItem("shareLogo");
      // 20241114版本，产品黄长发，分享链接改为只包含日程id，解决讲师分享日程详情，其他学员可以直接进入日程详情预约的问题，之前带学员id，只能指定学员进入
      let shareUrl = window.location.href.split("#")[0] + '#/edu/scheduleDetail?scheduleListId=' + this.scheduleListId + '&isShowAppointment=' + this.isShowAppointment + '&refereeId=' + localStorage.getItem("userId");
      let shareDesc = this.scheduleDetail.cName || "点击查看详情";
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { });
    },
    //手机端分享
    appShare: function () {
      let title = this.scheduleDetail.courseName;
      let shareImg = this.scheduleDetail.saleCourseCover || this.scheduleDetail.courseCover || 'https://knowledge-payment.oss-cn-beijing.aliyuncs.com/13/resource/admin-fe_lj7l_enlist_YeT7sJt3W2MmhWQreXZa.png' || window.localStorage.getItem("shareLogo");
      let shareUrl = window.location.href.split("#")[0] + '#/edu/scheduleDetail?scheduleListId=' + this.scheduleListId + '&isShowAppointment=' + this.isShowAppointment + '&refereeId=' + localStorage.getItem("userId");
      let shareDesc = this.scheduleDetail.cName || "点击查看详情";
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    },
  },
  activated() {
    window.scrollTo(0, 0);
    setDocumentTitle("日程详情");// eslint-disable-line
    this.studentId = this.$route.query.studentId || '';
    this.courseId = this.$route.query.courseId || '';
    this.scheduleListId = this.$route.query.scheduleListId || '';
    this.isShowAppointment = this.$route.query.isShowAppointment;
    this.orderId = this.$route.query.orderId ? this.$route.query.orderId : '';
    this.saleCourseId = this.$route.query.saleCourseId ? this.$route.query.saleCourseId : '';
    this.reservationResStatus = false;
    this.purchaseId = '';
    // this.saleCourseId = "";
    this.type = "";
    this.scheduleDetail = {};
    this.getScheduleDetail();
  },
  deactivated() {
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
